<template>
	<el-card shadow="never" class="admin_index_article">
		<template slot="header">
			<h4>文章访问量排名</h4>
			<el-radio-group v-model="scopeDate" size="mini">
				<el-radio-button label="day">今日</el-radio-button>
				<el-radio-button label="month">本月</el-radio-button>
				<el-radio-button label="year">全年</el-radio-button>
			</el-radio-group>
		</template>
		<div class="echarts" ref="chart"></div>
	</el-card>
</template>

<script>
import * as echarts from 'echarts';
import { getNewsRank } from '@/api/statistics';
const debounce = (func, wait) => {
	let timeout;
	return function () {
		const context = this;
		const args = arguments;
		clearTimeout(timeout);
		timeout = setTimeout(() => func.apply(context, args), wait);
	};
};
export default {
	data() {
		return {
			scopeDate: 'month',
			chartOption: {
				xAxis: { type: 'value', show: false },
				yAxis: {
					type: 'category',
					axisLabel: {
						fontSize: 14,
						lineHeight: 20,
						interval: false,
						formatter: function (value) {
							let nameValue = value.length > 16 ? value.slice(0, 15) + '...' : value;
							if (nameValue.length > 8) {
								return nameValue.slice(0, 8) + '\n' + nameValue.slice(8);
							}
							return nameValue;
						}
					}
				},
				grid: { top: 24, left: 0, right: 0, bottom: 0, containLabel: true },
				series: {
					type: 'bar',
					showBackground: true,
					label: { show: true, position: 'insideRight', fontSize: 14 },
					backgroundStyle: { color: 'rgba(180, 180, 180, 0.2)' },
					data: []
				}
			}
		};
	},
	watch: {
		scopeDate: {
			async handler(val) {
				await this.getNewsRankData(val);
				this.chartInstance.setOption(this.chartOption);
			},
			immediate: true
		}
	},
	mounted() {
		this.initializeChart();
		window.addEventListener(
			'resize',
			debounce(() => {
				this.chartInstance.resize();
			}, 200)
		);
	},
	methods: {
		initializeChart() {
			let chartDom = this.$refs['chart'];
			this.chartInstance = new echarts.init(chartDom);
		},

		async getNewsRankData(scope) {
			let params = { page: 1, limit: 5, opt: 'click', scope };
			let result = await getNewsRank(params).then((res) => res.data);
			if (result.code === '0') {
				let datas = (result.data || []).reverse();
				this.chartOption.yAxis.data = datas.map((item) => item.title);
				this.chartOption.series.data = datas.map((item) => Number(item.clickCount));
			}
		}
	}
};
</script>

<style lang="scss" scoped>
.admin_index_article {
	flex: 4;
	// height: calc(50% - 18px);
}
</style>
